package cn.javacart.jopencart.library;

import com.jfinal.kit.LogKit;

import cn.javacart.jopencart.engine.JOpencartController;
import cn.javacart.jopencart.engine.JOpencartModule;

/**
 * 模块加载
 * @author farmer
 *
 */
public class LoadService {

	private static LoadService loadService = null;
	
	/**
	 * 获取Load单例
	 * @return
	 */
	public static LoadService getInstance() {
		if(loadService == null){
			loadService = new LoadService();
		}
		return loadService;
	}

	/**
	 * 加载组件
	 * @return
	 */
	public String module(JOpencartModule module){
		return module.render();
	}
	
	/**
	 * 加载组件通过名称
	 * @param module
	 * @param controller
	 * @return
	 */
	public String module(String module ,JOpencartController controller){
		return module(module, controller, null);
	}

	/**
	 * 
	 * @param module
	 * @param controller
	 * @param extra
	 * @return
	 */
	public String module(String module, JOpencartController controller,
			Object extra) {
		try {
			LogKit.info("加载module："+module);
			Class<?> clazz = Class.forName(module);
			JOpencartModule moduleObject = null;
			if(extra == null){
				moduleObject = (JOpencartModule) clazz.getConstructor(JOpencartController.class).newInstance(controller);
			}else{				
				moduleObject = (JOpencartModule) clazz.getConstructor(JOpencartController.class,Object.class).newInstance(controller,extra);
			}
			return moduleObject.render();
		} catch (Exception e) {
			LogKit.error("加载"+module+"错误!",e);
			return "加载"+module+"错误!";
		}
	}
	
	
	
}